﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

using com.dz.ct.components;
using com.dz.ct.db;
using com.dz.ct.common;
using System.Threading;
using System.Text.RegularExpressions;
using System.Web;
using com.dz.ct.html;

namespace com.dz.ct.business
{


    public class BookCollectManager
    {
        #region 属性变量
        private DataSet m_baidu_ds = null;

        //文件读写
        FileManager m_file_mgr = new FileManager();
        /// <summary>
        /// 线程数量
        /// </summary>
        public int ThreadCount { get; set; }

        /// <summary>
        /// 盗版站点ID
        /// </summary>
        public int SiteId { get; set; }

        /// <summary>
        /// 需要收录章节的书籍
        /// </summary>
        private DataSet m_ds = null;

        /// <summary>
        /// 需要收录章节的书籍记录
        /// </summary>
        private int m_total_count = 0;

        /// <summary>
        /// 索引
        /// </summary>
        private int m_reg_index = 0;

        /// <summary>
        /// 每个线程的收录量
        /// </summary>
        private int m_per_thread_count = 0;

        /// <summary>
        /// 数据访问对象
        /// </summary>
        private DBManager m_db_mgr = new DBManager();

        /// <summary>
        /// 需要收录书籍的SQL
        /// </summary>
        public string BookSQL { get; set; }

        /// <summary>
        /// 接口对象
        /// </summary>
        IBigSiteObject t_obj = null;


        /// <summary>
        /// 触发发送消息的事件
        /// </summary>
        public event SendMsgEventHandler SendMsg;

        #region 收集书籍属性

        /// <summary>
        /// 书籍列表地址
        /// </summary>
        public string BookUrl { get; set; }

        /// <summary>
        /// 开始页码
        /// </summary>
        public int StartPageIndex { get; set; }

        /// <summary>
        /// 接口变量
        /// </summary>
        public string ComName { get; set; }

        #endregion

        /// <summary>
        /// 站点配置
        /// </summary>
        public DataRow SiteConfig { get; set; }

        /// <summary>
        /// 更新地址url
        /// </summary>
        public string LastUpdateUrl { get; set; }

        /// <summary>
        /// 结束页码
        /// </summary>
        public int EndPageIndex { get; set; }

        /// <summary>
        /// 一本书的sql语句
        /// </summary>
        private string m_single_book_sql = string.Empty;

        /// <summary>
        /// 最新更新的时间
        /// </summary>
        private DateTime m_last_update_time = DateTime.Now.AddDays(-1);


        #endregion

        #region 消息回送
        /// <summary>
        /// 发送消息到客户端
        /// </summary>
        /// <param name="i_msg"></param>
        private void SendMsg2Client(string i_msg, MsgType i_msg_type)
        {
            SendMsgEventArgs e = new SendMsgEventArgs();
            e.Msg = i_msg;
            e.MsgType = i_msg_type;
            if (SendMsg != null)
            {
                SendMsg(this, e);
            }

        }
        #endregion

        #region 收集书籍逻辑

        /// <summary>
        /// 收集小说详情
        /// </summary>
        public void StartCollectBook()
        {
            if (string.IsNullOrEmpty(ComName))
                return;

            t_obj = ComManager.CreateBigSiteObj(ComName);

            string t_book_url = string.Empty;

            BookInfo t_book_info = null;

            BookInfo t_result_book_info = null;

            List<BookInfo> t_book_list = null;

         
            try
            {
                if (EndPageIndex != 1)
                {

                    for (int index = StartPageIndex; index < EndPageIndex; index++)
                    {
                        t_book_url = string.Format(BookUrl, index);

                        t_book_list = t_obj.CollectBookList(t_book_url);

                        if (t_book_list != null && t_book_list.Count>0)
                        {
                            SendMsg2Client(string.Format("从地址：{0} 收录到{1}本小说", t_book_url, t_book_list.Count), MsgType.Total);

                            foreach (BookInfo t_book in t_book_list)
                            {
                                t_book_info = t_obj.CollectBookItem(t_book.BookCommentUrl);

                                t_book_info.BookId = Guid.NewGuid().ToString();

                                t_result_book_info = m_db_mgr.InsertBookInfo(t_book_info);

                                if (t_result_book_info!=null && string.IsNullOrEmpty(t_result_book_info.LastUpdateChapterId))
                                {
                                    SendMsg2Client(string.Format("小说：{0} 成功入库", t_book_info.BookName), MsgType.Detail);

                                    CollectNormalChapter(t_result_book_info);

                                }
                            }
                        }


                    }

                }
                else
                {
                    t_book_info = t_obj.CollectBookItem(BookUrl);

                    t_book_info.BookId = Guid.NewGuid().ToString();

                    t_result_book_info = m_db_mgr.InsertBookInfo(t_book_info);

                    if (t_result_book_info!=null && string.IsNullOrEmpty(t_result_book_info.LastUpdateChapterId))
                    {

                        SendMsg2Client(string.Format("小说：{0} 成功入库", t_book_info.BookName), MsgType.Detail);

                        //成功入库，下载小说封面及收录普通章节

                        CollectNormalChapter(t_result_book_info);
                       

                    }
                    else
                    {
                        SendMsg2Client(string.Format("小说：{0} 已经存在", t_book_info.BookName), MsgType.Detail);
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("收录小说信息失败" + ex.ToString());
            }

        }

        #endregion

        #region 普通章节收录逻辑

       

        private void CollectNormalChapter(BookInfo i_book_info)
        {
            t_obj = ComManager.CreateBigSiteObj(ComName);


            try
            {
                List<BookChapterInfo> t_chapter_list_source = t_obj.CollectChapterList(i_book_info.BookChapterListUrl);

                if (t_chapter_list_source == null && t_chapter_list_source.Count <= 0)
                    return;

                string t_last_update_chapter_name = i_book_info.LastUpdateChapterName;

                int t_chapter_index = 0;

                string t_chapter_content = string.Empty;

                if (t_chapter_list_source != null && t_chapter_list_source.Count > 0)
                {
                    SendMsg2Client(string.Format("地址：{0} 收集到{1}个章节..", i_book_info.BookChapterListUrl, t_chapter_list_source.Count), MsgType.Total);

                    if (!string.IsNullOrEmpty(t_last_update_chapter_name))
                    {
                        t_chapter_index = t_chapter_list_source.FindIndex(delegate(BookChapterInfo t_chapter_info)
                        {
                            return t_chapter_info.ChapterName== t_last_update_chapter_name;
                        });
                    }
                }
                if (t_chapter_index <= 0)
                    t_chapter_index = 0;
                else
                {
                    if (t_chapter_index == t_chapter_list_source.Count - 1)
                    {
                        return;
                    }
                    t_chapter_index++;
                }

                if (t_chapter_index >= t_chapter_list_source.Count-1)
                    return;

                string t_book_id = i_book_info.BookId;

                int t_ret = 0;

                string t_pre_chapter_id = i_book_info.LastUpdateChapterId;

                string t_chapter_id = Guid.NewGuid().ToString();

                //更新上一次收录的最后章节的下一章节id
                if (!string.IsNullOrEmpty(t_pre_chapter_id))
                {
                    m_db_mgr.UpdateLastUpdateChapterId(t_pre_chapter_id, t_chapter_id, Consts.GetTableName(t_chapter_list_source[0].SiteId));
                }

                string t_next_chapter_id = Guid.NewGuid().ToString();

                BookChapterInfo t_chapter = null;

                for (int index = t_chapter_index; index < t_chapter_list_source.Count; index++)
                {
                    t_chapter = t_chapter_list_source[index];

                    t_chapter.ChapterId = t_chapter_id;
                    t_chapter.PreChapterId = t_pre_chapter_id;
                    t_chapter.NextChapterId =(index==t_chapter_list_source.Count-1)?string.Empty: t_next_chapter_id;

                    t_chapter.BookId = t_book_id;
       
                    //章节信息保存到数据库
                    t_ret = m_db_mgr.InsertBookChapter(t_chapter);

                    //章节内容保存到磁盘
                    if (t_ret > 0)
                    {
                        SendMsg2Client(string.Format("收集到章节 ：{0}", t_chapter.ChapterName), MsgType.Detail);

                        t_pre_chapter_id = t_chapter_id;

                        t_chapter_id = t_next_chapter_id;

                        t_next_chapter_id = Guid.NewGuid().ToString();

                        
                    }

                }
                //更新小说表的最新更新章节信息及章节总数信息

                m_db_mgr.UpdateBookChapterInfo(Consts.GetTableName(t_chapter.SiteId), t_chapter.BookId,  t_chapter.ChapterId, t_chapter.ChapterName, t_chapter.UpdateTime, t_chapter_list_source.Count);

            }
            catch (Exception ex)
            {
                LogHelper.Error("收集普通章节失败" + ex.ToString());
            }
        }
        #endregion


        #region 收录最新章节
        /// <summary>
        /// 开始收录最新更新内容
        /// </summary>
        public void StartUpdateChapter()
        {
            string t_book_url = string.Empty;

            List<BookInfo> t_book_list = null;

            t_obj = ComManager.CreateBigSiteObj(ComName);

            int t_book_count=0;

            bool t_is_exit = false;

            BookInfo t_book_info=null;

            DateTime t_last_update_time = DateTime.Now.AddDays(-1);

            while (true)
            {
                Thread.Sleep(1000);

                for (int index = 1; index < 1000; index++)
                {
                    t_book_url = string.Format(LastUpdateUrl, index);

                    t_book_list = t_obj.CollectBookList(t_book_url);

                    foreach (BookInfo t_book in t_book_list)
                    {
                        t_book_count++;
                        if (t_book.LastUpdateTime < m_last_update_time)
                        {
                            SendMsg2Client(string.Format("此次更新了：{0}本小说，更新时间：{1}", t_book_count, t_book.LastUpdateTime), MsgType.Total);
                            t_is_exit = true ;
                            break;
                        }
                       

                        t_book_info = m_db_mgr.CheckBookEixsts(t_book.BookName, SiteId);

                        //小说不存在
                        if (t_book_info == null)
                        {
                            t_book_info = t_obj.CollectBookItem(t_book.BookUrl);

                            if (t_book_info != null)
                            {
                              
                                t_book_info.BookId = Guid.NewGuid().ToString();
                                t_book_info = m_db_mgr.InsertBookInfo(t_book_info);
                            }
                        }

                        t_last_update_time = t_book.LastUpdateTime;
                        if (t_book_info != null)
                        {
                            SendMsg2Client(string.Format("小说：{0}入库成功", t_book.BookName), MsgType.Total);
                            CollectNormalChapter(t_book_info);
                        }

                    }

                    if (t_is_exit)
                        break;
                }

                m_last_update_time = t_last_update_time;

                //休息6个小时
                Thread.Sleep(6 * 60 * 60 * 1000);
            }
        }
        #endregion


    }

}
